<?php
class Request {
	public static function getClientIp($returnInt = false)
	{
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), '0'))
		{
			$ip = getenv('HTTP_CLIENT_IP');
		}elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), '0'))
		{
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), '0'))
		{
			$ip = getenv('REMOTE_ADDR');
		}elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], '0'))
		{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		$ip =  preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : '0';
		if($returnInt) {
			$ip = ip2long($ip);
			$ip = sprintf("%u", floatval($ip)); //convert it to unsigned ip address.
		}
		return $ip;
	}

	public static function getUrl()   {
		if($_SERVER["SERVER_PORT"] != 80) {
			$http_prefix ='http://'.$_SERVER["SERVER_NAME"].':'.$_SERVER["SERVER_PORT"];
		}else $http_prefix ='http://'.$_SERVER["SERVER_NAME"];
		return $http_prefix.$_SERVER["REQUEST_URI"];
	}

	public static function getInt($name) {
		if(array_key_exists($name, $_GET) && is_numeric($_GET[$name])) {
			return intval($_GET[$name]);
		}
		return null;
	}

	/*
	public static function getStr($name) {
		if(array_key_exists($name, $_GET)) {
			return ($_GET[$name]);
		}
		return null;
	}*/
	public static function getStr($name) {
		if(array_key_exists($name, $_GET)) {
			$p = $_GET[$name];
			$p = trim($p);
			if(get_magic_quotes_gpc()) $p=stripslashes($p);
			$p = htmlspecialchars($p);
			return $p;
		}
		return null;
	}

	public static function getDouble($name) {
		if(array_key_exists($name, $_GET) && is_numeric($_GET[$name])) {
			return doubleval($_GET[$name]);
		}
		return null;
	}

	public static function getPostInt($name) {
		if(array_key_exists($name, $_POST) && is_numeric($_POST[$name])) {
			return intval($_POST[$name]);
		}
		return null;
	}
	
	public static function noCache()
	{
		if (!headers_sent())
		{
			header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
			header('Expires: ' . gmdate ("D, d M Y H:i:s", time()+0). " GMT");
			header('Cache-control:  no-cache, must-revalidate ');
			header('Etag: '.md5(time()));
			header('Pragma: no-cache');
		}
	}
	
	/*
	public static function getPostStr($name) {
		if(array_key_exists($name, $_POST)) {
			return ($_POST[$name]);
		}
		return null;
	}*/
	public static function getPostStr($name) {
		if(array_key_exists($name, $_POST)) {
			$p = $_POST[$name];
			$p = trim($p);
			if(get_magic_quotes_gpc()) $p=stripslashes($p);
			$p = htmlspecialchars($p);
			return $p;
		}
		return null;
	}

	public static function getPostDouble($name) {
		if(array_key_exists($name, $_POST) && is_numeric($_POST[$name])) {
			return doubleval($_POST[$name]);
		}
		return null;
	}

	public static function isPostMethod() {
		$is_post = ($_SERVER["REQUEST_METHOD"] == "POST");
		return $is_post;
	}
	
	public static function isGetMethod() {
		$is_get = ($_SERVER["REQUEST_METHOD"] == "GET");
		return $is_get;
	}
	
	
	public static function isAjaxRequest() {
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
			return true;
		return false;
	}
	
	/*filter an array
	 	input example: md5:key1,key2,base64_encode:key3!,intval:key4
		! means must, if it equals null then return false
		function_name:key, handle key to function_name
		key2=key1, rename key1 to key2

		e.g. $data = Request::filter($_GET,'id=intval:item_id!,action!,intval:category_id');
	*/
	public static function filter($arr,$keys,$write_global = false)
	{
		$re = array();
		$key_arr = explode(',',$keys);
		foreach($key_arr as $key)
		{
			$key = trim($key);
			if (!$key) continue;
			$_must = false;
			$_func = false;
			$_key = false;
			if (strpos($key,'=') !== false)
			{
				$_arr = explode('=',$key);
				$_key = $_arr[0];
				$key = $_arr[1];
			}
			if (strpos($key,'!') !== false)
			{
				$_must = true;
				$key = str_replace('!','',$key);
			}
			if (strpos($key,':') !== false)
			{
				$_arr = explode(':',$key);
				$_func = $_arr[0];
				$key = $_arr[1];
			}
			!$_key && $_key = $key;
			if ($_func && function_exists($_func))
				if (@eval('$arr[$key] = '.$_func.'($arr[$key]);') === false) return false;
			if ($_must && !$arr[$key]) 
				return false;
			else
				$re[$_key] = isset($arr[$key])?$arr[$key]:NULL;
		}
		if ($write_global)
		{
			foreach($re as $key => $val)
			{
				$GLOBALS[$key] = $val;
			}
		}
		return $re;
	}
	
	/**
	 * 检查是否是搜索引擎蜘蛛
	 * @return bool
	 */
	static function isSpider() {
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
		if(strpos($userAgent,"http")) {
			return true;
		}
		return false;
	}
	
	static function isQQSharingSpider(){
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
		if(strpos($userAgent,"http://www.bsalsa.com/")) {
			return true;
		}
		return false;
	}
	
	public static function g2u($str){
		if(mb_detect_encoding($str, array("ASCII","UTF-8","GB2312","GBK","BIG5")) != "EUC-CN"){
			return $str;
		}else{
			return iconv('gb2312', 'utf-8', $str);
		}
	}
	
	//返回 1 表示纯 ASCII(即是所有字符都不大于127)
	//返回 2 表示UTF8
	//返回 0 表示正常gb编码
	public static function TestUtf8($text)
	{
	    if(strlen($text) < 3) return false;
	    $lastch = 0;
	    $begin = 0;
	    $BOM = true;
	    $BOMchs = array(0xEF, 0xBB, 0xBF);
	    $good = 0;
	    $bad = 0;
	    $notAscii = 0;
	    for($i=0; $i < strlen($text); $i++)
	    {
	        $ch = ord($text[$i]);
	        if($begin < 3)
	        {
	            $BOM = ($BOMchs[$begin]==$ch);
	            $begin += 1;
	            continue;
	        }

	        if($begin==4 && $BOM) break;

	        if($ch >= 0x80 ) $notAscii++;

	        if( ($ch&0xC0) == 0x80 )
	        {
	            if( ($lastch&0xC0) == 0xC0 )
	            {
	                 $good += 1;
	            }
	            else if( ($lastch&0x80) == 0 )
	               {
	              $bad += 1;
	            }
	        }
	        else if( ($lastch&0xC0) == 0xC0 )
	        {
	                $bad += 1;
	        }
	        $lastch = $ch;
	    }
	    if($begin == 4 && $BOM)
	    {
	        return 2;
	    }
	    else if($notAscii==0)
	    {
	        return 1;
	    }     
	    else if ($good >= $bad )
	    {
	        return 2;
	    }
	    else
	    {
	       return 0;
	    }
	}
	
}
?>